/*
 * Copyright 2006-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.martinimix.view.common.html;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Provides methods for creating an HTML tag.
 * 
 * @author Scott Rossillo
 *
 */
public class HTMLTag {
	
	private final String name;
	private final Map propMap = new HashMap();
	private boolean hasBody = false;
	
	protected HTMLTag(String name) {
		
		this.name = name;
	}
	
	public String doStartTag() {
		
		StringBuffer buf = new StringBuffer();
		
		buf.append("<");
		buf.append(name);
		
		Iterator it = propMap.keySet().iterator();
		
		while(it.hasNext()) {
			String key = (String) it.next();
			buf.append(' ');
			buf.append(key);
			buf.append("=\"");
			buf.append(propMap.get(key));
			buf.append("\"");
		}
	
		buf.append(hasBody ? ">" : "/>");
		
		return buf.toString();
	}
	
	public String doEndTag() {
		
		String endTag = null;
		
		if(hasBody) {
			endTag = "</" + name + ">";
		}
		
		return endTag;
	}
	
	/**
	 * Returns the value stored for the given key.
	 * 
	 * @param key 
	 * 
	 * @return the value stored for the given <code>key</code>
	 * or <code>null</code> if <code>key</code> does not exist in this tag
	 */
	public String get(String key) {
		return (String) propMap.get(key);
	}
	
	public boolean hasBody() {
		return hasBody;
	}
	
	public void setBody(boolean hasBody) {
		this.hasBody = hasBody;
	}
	
	public boolean put(String key, String value) {
		
		if(key == null) {
			throw new NullPointerException("Property key cannot be null!");
		}
		
		if(value == null) {
			return false;
		}
		
		propMap.put(key.toLowerCase(), value);
	
		return true;
	}
	
	public String toString() {
	
		StringBuffer buf = new StringBuffer();
		
		buf.append("<");
		buf.append(name);
		
		Iterator it = propMap.keySet().iterator();
		
		while(it.hasNext()) {
			String key = (String) it.next();
			buf.append(' ');
			buf.append(key);
			buf.append("=\"");
			buf.append(propMap.get(key));
			buf.append("\"");
		}
		
		buf.append("/>");
		
		return buf.toString();
	}

}
